package org.demo.controller.impl;

import org.demo.controller.IReadBackController;
import org.demo.model.impl.FireHoseLoader;
import org.demo.model.impl.QSaharaServer;
import org.demo.utils.Command;
import org.demo.utils.CommandCallback;
import org.demo.view.IReadBackView;

public class ReadBackControllerImpl implements IReadBackController {

	private IReadBackView view;

	public ReadBackControllerImpl(IReadBackView view) {
		this.view = view;
	}

	@Override
	public void execute() {
		view.disableExecute();
		view.updateProgress(0);
		QSaharaServer server = new QSaharaServer.Builder().server(view.getQSaharaServerPath())
				.firehose(view.getProgrammerPath()).port(view.getCOMPort()).build();
		Command.execute(server.cmd(), view.getOutputPath(), new CommandCallback() {

			@Override
			public void updateProgress(int progress) {
				view.updateProgress(progress);
			}

			@Override
			public void updateLog(String message) {
				view.updateLog(message);
			}

			@Override
			public void success() {
				FireHoseLoader loader = new FireHoseLoader.Builder().loader(view.getFireHoseLoaderPath())
						.port(view.getCOMPort()).sendXml(view.getRawprammPath()).searchPath(view.getSearchPath())
						.memoryName(view.getDeviceType()).reset(view.isReset()).useVerbose(view.isUseVerbose())
						.build();
				Command.execute(loader.cmd(), view.getOutputPath(), new CommandCallback() {

					@Override
					public void updateProgress(int progress) {
						view.updateProgress(progress);
					}

					@Override
					public void updateLog(String message) {
						view.updateLog(message);
					}

					@Override
					public void success() {
						view.enableExecute();
						view.success();
					}

					@Override
					public void failure(String error) {
						view.enableExecute();
						view.failure(error);
					}
				});
			}

			@Override
			public void failure(String error) {
				view.enableExecute();
				view.failure(error);
			}
		});

	}

}
